
// Definition for a binary tree node.
function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}

/**
 * @param {TreeNode} root
 * @return {number[][]}
*/
var levelOrder = function(root) {
  let nodeArr = [], result = [];
  function preView(node, depth) {
    if(!node) return;
    nodeArr.push({
      val: node.val,
      depth
    });
    preView(node.left, depth + 1);
    preView(node.right, depth + 1);
  }
  preView(root, 0);
  nodeArr.sort((a, b) => a.depth - b.depth);
  for(let i = 0; i < nodeArr.length; i++) {
    if(result[nodeArr[i].depth] == undefined) {
      result[nodeArr[i].depth] = [nodeArr[i].val];
    } else {
      result[nodeArr[i].depth].push(nodeArr[i].val);
    }
  }
  return result;
};
